// create namespace
Ext.namespace('zr.dms');


zr.dms.objid  = null;
zr.dms.fk_annex_id = null; 
// create application
zr.dms.Manager = function() {
	// do NOT access DOM from here; elements don't exist yet

	// private variables
	var folderTreePanel = null;
	var sharedFolderTreePanel = null;
	var listGrid = null;
	var searchResultGrid = null;
	var myWorkSpaceGrid = null;
	var workSpaceGrid = null;
	var workSpaceTabPanel = null;
	var shareGrid = null;
	var mainPanel = null;
	var accordionPanel = null;
	var mainMenu = null;
	var shareDocMenu = null;
	var workSpaceMenu = null;
	var contextMenu = null;
	var contextMenu4SingleFile = null;
	var contextMenu4SingleFolder = null;
	var contextMenu4Mix = null;
	var contextMenu4MyShare = null;
	// 地址栏
	var addressBar = null;
	var fileInfoWindow = null;
	//目录访问路径记录数组
	var pathArray = [];
	//共享文件目录访问路径记录数组
	var sharePathArray= [];
	// private functions
	/**
	 * 树节点被点击时的事件处理
	 */
	function onTreeNodeClicked(node, e) {
		var sm = listGrid.getSelectionModel();
		sm.clearSelections();
		mainPanel.setActiveTab('fileListGrid');
		listGrid.loadList(node.id, node.text);
		if (node.id == '-1') {
			addressBar.setAddress('', '');
		} else {
			var pathId = node.attributes.fullpathId + '/' + node.id;
			var pathName = node.attributes.fullpath + '/' + node.text;
			addressBar.setAddress(pathId, pathName);
		}

	}
	
	
	/**
	 * 共享文档树节点被点击时的事件处理
	 */
	function onSTreeNodeClicked(node, e) {
		//var sm = shareGrid.getSelectionModel();
		//sm.clearSelections();
		mainPanel.setActiveTab('shareGrid');
		shareGrid.loadList(node.id, node.text);


	}

	/**
	 * 列表Panel列表行被双击时的事件处理
	 */
	function onListGridRowDblClicked(grid, rowIndex, e) {
		var selectionModel = grid.getSelectionModel();
		var record = selectionModel.getSelected();
		var objkey = record.data.objkey;
		zr.dms.fk_annex_id = record.data.id;
		zr.dms.objid = record.data.objid;
		if (objkey == "FILEINFO") {
			//window.open(context + '/app/dms.do?method=download&fk_annex_id='+ fk_annex_id);
			//Ext.getCmp('content-panel').layout.setActiveItem('fileInfoTabs');
			//fileInfoTabs.objId = record.data.objid;
			//fileInfoTabs.objFk_annex_id = fk_annex_id;
			//fileInfoTabs.activate(0); 
			fileInfoWindow.fileType = "mine";
			fileInfoWindow.showWindow(record);
			
		} else {
			currentfolderid = record.data['id'];
			listGrid.loadList(currentfolderid, name);
			accordionPanel.layout.setActiveItem('folderTree');
			folderTreePanel.expandNode(currentfolderid);
			var node = folderTreePanel.getNodeById(currentfolderid);
			folderTreePanel.fireEvent("click", node);
		}

	}
	
	/**
	 * 查询结果列表Panel列表行被双击时的事件处理
	 */
	function onSListGridRowDblClicked(grid, rowIndex, e) {
		var selectionModel = grid.getSelectionModel();
		var record = selectionModel.getSelected();
		var objkey = record.data.objkey;
		zr.dms.fk_annex_id = record.data.id;
		zr.dms.objid = record.data.objid;
		if (objkey == "FILEINFO") {
			fileInfoWindow.fileType = "mine";
			fileInfoWindow.showWindow(record);
			
		} else {
			mainPanel.setActiveTab('fileListGrid');
			currentfolderid = record.data['id'];
			listGrid.loadList(currentfolderid, name);
			//左侧导航树展开，导航条显示路径
			expendFolder(record.data.id);
			
		}

	}
	
	/**
	 * 共享区列表双击事件
	 */
	function onWsListGridRowDblClicked(grid, rowIndex, e){
		var selectionModel = grid.getSelectionModel();
		var record = selectionModel.getSelected();
		var objkey = record.data.objkey;
		zr.dms.fk_annex_id = record.data.id;
		zr.dms.objid = record.data.objid;
		if (objkey == "FILEINFO") {
			fileInfoWindow.fileType = "workspace";
			fileInfoWindow.showWindow(record);
		} else {
			currentfolderid = record.data['id'];
			grid.loadList(currentfolderid, record.data['filename']);
			
		}

	}
	
	/**
	 * 共享文档列表双击事件
	 */
	function onShareGridDblClicked(grid, rowIndex, e){
		var selectionModel = grid.getSelectionModel();
		var record = selectionModel.getSelected();
		var objkey = record.data.objkey;
		zr.dms.fk_annex_id = record.data.id;
		zr.dms.objid = record.data.objid;
		if (objkey == "FILEINFO") {
			fileInfoWindow.fileType = "workspace";
			fileInfoWindow.showWindow(record);
		} else {
			currentfolderid = record.data['id'];
			grid.loadList(currentfolderid, record.data['filename']);
			accordionPanel.layout.setActiveItem('SharedFolderTree');
			sharedFolderTreePanel.expandNode(currentfolderid);
			
		}

	}
	
	/**
	 * 根据文件夹id获取其路径
	 */
	function expendFolder(fid){
		var path ;
		var pathId;
		Ext.Ajax.request({
		   url: context + '/app/dms.do?method=getPath',
		   method : 'POST',
		   params: { fid: fid },
		   success : function(response,action) {
          var respText = Ext.util.JSON.decode(response.responseText); //字符串变为json格式  
          path = respText.path;
          pathId = respText.pathid;
          folderTreePanel.expandPath("/-1"+pathId);
          addressBar.setAddress(pathId, path);
         },  
         failure : function(response,options) {  
         }
		});

		return path;
		
	}


	/**
	 * 地址栏跳转按钮被点击时的处理
	 */
	function onGoClicked(toolbar) {
		var fullpathId = toolbar.getAddress();
		var fullpath = toolbar.getAddressText();
		var idx = fullpathId.lastIndexOf('/');
		var idx2 = fullpath.lastIndexOf('/');
		var nodeId =  fullpathId.substring(idx+1,fullpathId.length);
		var nodeName = fullpath.substring(idx2+1,fullpath.length);
		mainPanel.setActiveTab('fileListGrid');
		listGrid.loadList(nodeId,"");
		folderTreePanel.expandPath('/-1'+fullpathId);
		
		//记录目录访问路径
		if(nodeId != -1){
		pathArray.push([nodeId,nodeName,fullpathId]);
		}
		
	}
	
	/**
	 * 地址栏搜索按钮被点击时的处理
	 */
	function onQueryClicked(toolbar) {
		var queryText = Ext.get('queryText').dom.value;
		if(queryText != ""){
		mainPanel.setActiveTab('searchResultGrid');
		searchResultGrid.loadList(queryText);
		}
		
		
	}
	
	/**
	 * 高级查询
	 */
	function onSQueryClicked(params) {
		mainPanel.setActiveTab('searchResultGrid');
		searchResultGrid.loadSQueryList(params);
	}
	
	/**
	 * 记录文件夹浏览轨迹，用于后退、前进操作
	 */
	function recordPath(node, e){
		var nodeId = node.id;
		var nodeName = node.text;

		if(node.id != -1){
		var path = node.attributes.fullpathId + '/' + node.id;
		pathArray.push([nodeId,nodeName,path]);
		}
		
	}
	
	function recordSharePath(node, e){
		var nodeId = node.id;
		var nodeName = node.text;
		var path = node.attributes.fullpathId + '/' + node.id;
		sharePathArray.push([nodeId,nodeName,path]);
		
	}
	
	/**
	 * 列表窗口右键事件处理
	 */
	function onListGridContextMenu(e) {
		//如果事件是落在表格行上则不予处理，留待表格行事件完成
		e.preventDefault();
		/*var t = e.getTarget();
        var v = listGrid.getView();
        var row = v.findRowIndex(t);
        if(row != false) {
        	return;
        }
		e.preventDefault();
		contextMenu.showAt(e.getXY());
		var items = contextMenu.items;
		// 计算当前各菜单项状态
		var sm = listGrid.getSelectionModel();
		if(sm.getCount() == 0) {
			items.get('ctxMenuCopy').disable();
			items.get('ctxMenuCut').disable();
			items.get('ctxMenuDelete').disable();
			items.get('ctxMenuEditFolder').disable();
			items.get('ctxMenuEditInfo').disable();
		} else {
			items.get('ctxMenuCopy').disable();
			items.get('ctxMenuCut').disable();
			items.get('ctxMenuDelete').disable();
			items.get('ctxMenuEditFolder').disable();
			items.get('ctxMenuEditInfo').disable();
		}*/
	}
	
	/**
	 * 列表窗口数据行右键事件处理
	 */
	function onListGridRowContextMenu(grid, rowIndex, e) {
		e.preventDefault();
		//contextMenu.showAt(e.getXY());
		var view = grid.getView();
	   var rowIndex = view.findRowIndex(e.getTarget());
	   var record = grid.getStore().getAt(rowIndex);
	   if(rowIndex){
	   	    var selectedMe = false;
	   		var selectedNodes = grid.getSelectionModel().getSelections();
			for (var i = 0; i < selectedNodes.length; i++) {
				if (selectedNodes[i].data.objid == record.data.objid) {
					selectedMe = true;
				}

			}
	   	
			if(!selectedMe){
				grid.getSelectionModel().clearSelections() 
			}
			
	    //如果鼠标在有效的grid 范围内，则把当前grid选中
	    grid.getSelectionModel().selectRow(rowIndex,true);
	   }
		
		var record = grid.getStore().getAt(rowIndex); 
		//只有单选文件夹时才能“编辑文件夹”
		var hasFolder = false;
		var sm = grid.getSelectionModel();
		if(sm.hasSelection()) {
			var m = sm.getSelections();
			/*for(var i = 0; i < m.length; i++) {
				var objkey = m[0].get('objkey');
				if(objkey == 'FOLDER' ) {
					hasFolder = true;
				}
			}*/

			if(m.length == 1 && m[0].get('objkey')=='FOLDER') {
				contextMenu4SingleFolder.showAt(e.getXY());
			} else if(m.length == 1 && m[0].get('objkey')=='FILEINFO') {
				if(filetypes.indexOf(record.data.style) >= 0) {
					Ext.getCmp('ctxMenu4SfileEdit').enable();
				}else{
					Ext.getCmp('ctxMenu4SfileEdit').disable();
				}
				contextMenu4SingleFile.showAt(e.getXY());
			} else {
				contextMenu4Mix.showAt(e.getXY());
			}
			
		} else {
		}
	};
	
	
	/**
	 * 共享文件列表右键事件
	 */
	function onMyShareGridRowContextMenu(grid, rowIndex, e) {
		e.preventDefault();
		var view = grid.getView();
	   var rowIndex = view.findRowIndex(e.getTarget());
	   var record = grid.getStore().getAt(rowIndex);
	   if(rowIndex){
	   	    var selectedMe = false;
	   		var selectedNodes = grid.getSelectionModel().getSelections();
			for (var i = 0; i < selectedNodes.length; i++) {
				if (selectedNodes[i].data.objid == record.data.objid) {
					selectedMe = true;
				}

			}
	   	
			if(!selectedMe){
				grid.getSelectionModel().clearSelections() 
			}
			
	    //如果鼠标在有效的grid 范围内，则把当前grid选中
	    grid.getSelectionModel().selectRow(rowIndex,true);
	   }
		
		var record = grid.getStore().getAt(rowIndex); 
		//只有单选文件夹时才能“编辑文件夹”
		var hasFolder = false;
		var sm = grid.getSelectionModel();
		if(sm.hasSelection()) {
			var m = sm.getSelections();
			
			contextMenu4MyShare.showAt(e.getXY());

			
		} else {
		}
	};
	
	

	// public space
	return {
		// public properties, e.g. strings to translate

		// public methods
		init : function() {
			Ext.QuickTips.init();
			folderTreePanel = new zr.dms.FolderTree({});
			sharedFolderTreePanel = new zr.dms.SharedFolderTree({});
			mainMenu = new zr.dms.MainMenu({
						manager : this
					});
			shareDocMenu = new zr.dms.ShareDocMenu({manager : this});
			//contextMenu = new zr.dms.ContextMenu({ mainMenu: mainMenu});
			addressBar = new zr.dms.AddressBar();
			listGrid = new zr.dms.ListGrid({tbar:mainMenu});
			shareGrid = new zr.dms.ShareGrid({tbar:shareDocMenu});
			searchResultGrid = new zr.dms.SearchResultGrid();
			myWorkSpaceGrid = new zr.dms.MyWorkSpaceGrid();
			workSpaceGrid = new zr.dms.WorkSpaceGrid();
			fileInfoWindow = new zr.dms.fileInfoWindow();
			
			contextMenu4SingleFile = new zr.dms.ContextMenu4SingleFile({ mainMenu: mainMenu});
			contextMenu4SingleFolder = new zr.dms.ContextMenu4SingleFolder({ mainMenu: mainMenu});
			contextMenu4Mix = new zr.dms.ContextMenu4Mix({ mainMenu: mainMenu});
			contextMenu4MyShare = new zr.dms.CtxMenu4Myshare({ mainMenu: mainMenu});
			workSpaceMenu = new zr.dms.WorkSpaceMenu({
						manager : this
					});
			
			workSpaceTabPanel = new Ext.TabPanel({
				title :'共享设置',
				activeTab: 0,
				plain:true,
				defaults:{autoScroll: true},
				tabPosition: 'bottom',
				items:[myWorkSpaceGrid,workSpaceGrid
        		]
			});
			mainPanel = new zr.dms.MainPanel({
				listGrid: listGrid,
				shareGrid : shareGrid,
				myWorkSpaceGrid : myWorkSpaceGrid,
				workSpaceGrid:workSpaceTabPanel,
				searchResultGrid: searchResultGrid
			});
			// 界面同步
			folderTreePanel.on('click', onTreeNodeClicked, this);
			folderTreePanel.on('click', recordPath, this);
			sharedFolderTreePanel.on('click', onSTreeNodeClicked, this);
			sharedFolderTreePanel.on('click',recordSharePath, this);
			listGrid.on('rowdblclick', onListGridRowDblClicked, this);
			listGrid.on('rowcontextmenu', onListGridRowContextMenu, this);
			listGrid.on('contextmenu', onListGridContextMenu, this);
			searchResultGrid.on('rowdblclick', onSListGridRowDblClicked, this);
			//myWorkSpaceGrid.on('rowdblclick', onListGridRowDblClicked, this);
			myWorkSpaceGrid.on('rowcontextmenu', onMyShareGridRowContextMenu, this);
			workSpaceGrid.on('rowdblclick', onWsListGridRowDblClicked, this);
			shareGrid.on('rowdblclick', onShareGridDblClicked, this);
			addressBar.on('goClicked', onGoClicked, this);
			addressBar.on('queryClicked', onQueryClicked, this);
			addressBar.on('onSQueryClicked', onSQueryClicked, this);
			var contentPanel = {
				id : 'content-panel',
				region : 'center', // this is what makes this panel into a
									// region within the containing layout
				layout : 'card',
				margins : '2 5 5 0',
				activeItem : 0,
				border : false,
				items : [
				// from grid.js:,
				mainPanel]
			};
			
			//左侧导航树区域
			accordionPanel = new Ext.Panel({
			    id : 'accordionPanel',
			    layout : 'accordion',
				region : 'west',
				split : true,
				margins : '2 0 5 5',
				width : 200,
				items : [folderTreePanel, sharedFolderTreePanel]
			});


			new Ext.Viewport({
				layout : 'border',
				title : 'DocManageSystem',
				items : [{
					region : 'north',
					height : 56,
					layout : 'border',
					border : false,
					items : [{
								region : 'north',
								height : 28,
								//html : '<div id="header"><h1>文档管理系统</h1></div>'
								html : '<table  id="header" style="width:100%;" boder=0><tr><td width=70%><h1>文档管理系统</h1></td><td width=30% align="right" ><div id="logout">'+userName+(isAdmin?'|<a title="系统控制台" href="'+context+'/system/console" target="_blank">系统控制台</a>':'')+'|<a title="退出" href="javascript:void(0);" onclick="javascript:logout();">退出</a></div></td></tr></table>'
							}, {
								region : 'center',
								layout : 'hbox',
								padding : '0',
								align : 'top',// {xtype:'spacer',flex:1},
								items : [addressBar]
							}]
				},
				accordionPanel,
				contentPanel],
				renderTo : Ext.getBody()
			});

			listGrid.loadList('-1', '');
			workSpaceGrid.loadList();
			myWorkSpaceGrid.loadList();
		},
		/**
		 * 树组件访问方法
		 */
		getFolderTree : function() {
			return folderTreePanel;
		},
		
		getSharedFolderTreePanel : function(){
		 return sharedFolderTreePanel;
		},

		/**
		 * 返回grid
		 */
		getGridList : function() {
			return listGrid;
		},
		
		/**
		 * 返回shareGrid
		 */
		getShareGrid : function() {
			return shareGrid;
		},
		
		getMyShareGrid :function(){
			return myWorkSpaceGrid;
		},
		/**
		 * 返回工作区列表对象
		 */
		getWorkSpaceGrid: function() {
			return workSpaceGrid;
		},
		
		/**
		 * 返回addressBar
		 */
		getAddressBar : function(){
			return addressBar;
		},
		
		/**
		 * 获取文件夹访问记录
		 */
		getPathArray: function(){
			return pathArray;
		},
		
		/**
		 * 获取共享文件访问记录
		 */
		getSharePathArray: function(){
			return sharePathArray;
		}

	};
}();

/**
 * 页面主Panel
 */
zr.dms.MainPanel = function(config) {
	
	Ext.apply(this, config);
	zr.dms.MainPanel.superclass.constructor.call(this, {
		id :'mainPanel',
		layoutOnTabChange :true,
		activeTab: 'fileListGrid',
		items: [this.listGrid,
		this.shareGrid,
		this.workSpaceGrid,
		this.searchResultGrid]
	});
};

Ext.extend(zr.dms.MainPanel, Ext.TabPanel, {
	/** 检索结果grid */
	searchResultGrid: null,
	/** 列表grid */
	listGrid: null,
	/** 共享文档列表*/
	shareGrid: null,
	/** 工作区grid*/
	workSpaceGrid: null,
	/** 工作区我共享的文档grid*/
	myWorkSpaceGrid : null,
	/**
	 * 将指定的panel设置为当前激活的panel
	 */
	setActivePanel: function(id){
		if(this.getActiveTab().getId() == id) {
			return;
		}
		this.setActiveTab(id);
	},
	
	/**
	 * 返回搜索列表对象
	 */
	getSearchResultGrid: function() {
		return this.searchResultGrid;
	},
	
	/**
	 * 返回我的文档列表对象
	 */
	getListGrid: function() {
		return this.listGrid;
	},
	
	/**
	 * 返回共享文档列表对象
	 */
	getShareGrid: function() {
		return this.shareGrid;
	},
	/**
	 * 返回工作区列表对象
	 */
	getWorkSpaceGrid: function() {
		return this.workSpaceGrid;
	},
	
	/**
	 * 返回工作区列表对象
	 */
	getMyWorkSpaceGrid: function() {
		return this.myWorkSpaceGrid;
	},
	/**
	 * 返回当前激活的列表对象
	 */
	getActiveGrid: function() {
		if(this.getActiveTab().getId() == 'searchPanel') {
			return this.searchResultGrid;
		} else {
			return this.listGrid;
		}
	}
});

Ext.onReady(zr.dms.Manager.init, zr.dms.Manager);

function logout(){
	if(confirm('确定退出') == true){
		window.location.href = context + '/system/logout.do';
	}
}